package cn.yoyo.service;

import cn.yoyo.dao.BlogDao;
import cn.yoyo.dao.FavouriteDao;
import cn.yoyo.entity.Blog;
import cn.yoyo.entity.Favourite;
import cn.yoyo.tools.MySession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class FavouriteServiceImpl implements FavouriteService {
    @Autowired
    FavouriteDao favouriteDao;
    @Autowired
    BlogDao blogDao;

    @Override
    public void add(String blogId) {
        favouriteDao.add(new Favourite(blogId,MySession.getUserId()));
        Blog blog = blogDao.findById(blogId);
        Map<String,Object> map = new HashMap<>();
        map.put("blogId",blog.getId());
        map.put("favouriteSum",blog.getFavouriteSum()+1);
        blogDao.updateSum(map);
    }

    @Override
    public void delete(Favourite favourite) {
        favouriteDao.delete(favourite.getId());
        Blog blog = blogDao.findById(favourite.getBlogId());
        if (blog.getFavouriteSum()>0){
            Map<String,Object> map = new HashMap<>();
            map.put("blogId",blog.getId());
            map.put("favouriteSum",blog.getFavouriteSum()-1);
            blogDao.updateSum(map);
        }
        favouriteDao.delete(favourite.getId());
    }
}
